<template>
  <text>{{ displayTime }}</text>
</template>

<script>
export default {
  props: {
    // 目标时间戳（毫秒）
    endTime: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      timer: null,
      remaining: 0,
    };
  },
  computed: {
    displayTime() {
      if (this.remaining <= 0) return "已结束";
      const h = String(Math.floor(this.remaining / 3600)).padStart(2, "0");
      const m = String(Math.floor((this.remaining % 3600) / 60)).padStart(
        2,
        "0"
      );
      const s = String(this.remaining % 60).padStart(2, "0");
      return `${h}:${m}:${s}`;
    },
  },
  mounted() {
    this.update();
    this.timer = setInterval(this.update, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    update() {
      const now = Math.floor(Date.now() / 1000);
      this.remaining = Math.max(0, Math.floor(this.endTime / 1000) - now);
      if (this.remaining === 0) {
        this.$emit('finished');
        clearInterval(this.timer); // 停止定时器，防止多次触发
      }
    },
  },
};
</script>
